<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:activity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:activity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:activity:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="title" />
      <el-table-column label="活动封面" align="center" prop="imgs">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 50px" :src="scope.row.imgs | fullImgUrl" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.startTime) }}</div>
          <div>{{ parseTime(scope.row.endTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="活动描述" align="center" prop="desc" />
      <el-table-column label="浏览量/转发量" align="center" prop="views">
        <template slot-scope="scope">
          <span>{{ scope.row.views }}/{{ scope.row.shareTimes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态操作" align="center" prop="status" width="150">
        <template slot-scope="scope">
          活动状态 <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row, 'status')"></el-switch>
          <br>
          首页推荐 <el-switch v-model="scope.row.isIndex" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row, 'isIndex')"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="活动规模/用户等级" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.num }} / {{ getLevelFormat(scope.row.userLevel) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名列表" align="center" width="140px">
        <template slot-scope="scope">
         <el-button type="primary" size="mini" @click="handleOpenMsgList(scope.row.id)">查看报名【{{scope.row.applyNum}}】</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:activity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            class="text-red"
            icon="el-icon-remove-outline"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:activity:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动规模" prop="num">
          <el-input v-model="form.num" placeholder="请输入参与人数" />
        </el-form-item>
        <el-form-item label="参与用户等级" prop="userLevel">
          <el-select v-model="form.userLevel" placeholder="请选择">
            <el-option
              v-for="item in levelList"
              :key="item.id"
              :label="item.level"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="startTime">
          <el-date-picker clearable
            v-model="dateRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="handleDateRange"
            :default-time="['09:00:00', '21:00:00']"
            >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="省市区" prop="province">
          <el-cascader v-model="area" :options="areaOptions" :props="{value: 'label'}" @change="handleAreaChange" ></el-cascader>
        </el-form-item>
        <el-form-item label="活动地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="活动描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="活动封面" prop="imgs">
          <el-upload ref="img" :show-file-list="false" :action="imgAction" :before-upload="beforeUpload"
            :on-success="(res)=> uploadSuccess(res, 'imgs')" list-type="picture-card" accept="image/*">
            <img v-if="form.imgs" :src="form.imgs | fullImgUrl" width="148" height="148" style="object-fit: contain;" />
            <i v-else class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传不超过 <b style="color: red;">5MB</b> 的 <b style="color: red;">png/jpg/jpeg</b>文件，且不超过1个</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动分享封面" prop="shareImg">
          <el-upload ref="img" :show-file-list="false" :action="imgAction" :before-upload="beforeUpload"
            :on-success="(res)=> uploadSuccess(res, 'shareImg')" list-type="picture-card" accept="image/*">
            <img v-if="form.shareImg" :src="form.shareImg | fullImgUrl" width="148" height="148" style="object-fit: contain;" />
            <i v-else class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传不超过 <b style="color: red;">5MB</b> 的 <b style="color: red;">png/jpg/jpeg</b>文件，且不超过1个</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="报名价" prop="price">
          <el-input v-model="form.price" placeholder="请输入参与费用" />
        </el-form-item>
        <el-form-item label="推荐奖励积分" prop="jf">
          <el-input v-model="form.jf" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="签到奖励积分" prop="signJf">
          <el-input v-model="form.signJf" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="客服" prop="kf">
          <el-input v-model="form.kf" placeholder="请输入客服" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.business_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="报名列表" :visible.sync="msgVisible" width="980px" append-to-body  v-if="msgVisible">
      <ApplyList :activeId="activeId" />
    </el-dialog>
  </div>
</template>

<script>
import { listActivity, getActivity, delActivity, addActivity, updateActivity } from "@/api/mobile/activity"
import { listLevel } from "@/api/mobile/level"
import { regionData } from 'element-china-area-data';
import ApplyList from "./applyList.vue";

export default {
  name: "Activity",
  dicts: ['business_status'],
  components: {
    ApplyList
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      msgVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        userLevel: null,
        desc: null,
        province: null,
        city: null,
        zone: null,
        address: null,
        num: null,
        price: null,
        jf: null,
        imgs: null,
        shareImg: null,
        startTime: null,
        endTime: null,
        signTime: null,
        content: null,
        speaker: null,
        signJf: null,
        evaluateJf: null,
        status: null,
        activeStatus: null,
        kf: null,
        shareTimes: null,
        views: null,
        sort: null,
        isIndex: null,
        createdAt: null,
        updatedAt: null
      },
      // 在 data 中定义省市区数据
      areaOptions: regionData,
      area: [],
      dateRange: [],
      levelList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      activeId: '',
      imgAction: `${process.env.VUE_APP_BASE_API}/common/commonUpload`,
    }
  },
  created() {
    listLevel(this.queryParams).then(response => {
      this.levelList = response.rows
    });
    this.getList()
  },
  methods: {
    getLevelFormat(status) {
      const dart = this.levelList.find(item => item.id === status);
      if (dart) {
        return dart.level;
      } else {
        return '未知';
      }
    },
    handleOpenMsgList(id) {
      this.activeId = id;
      this.msgVisible = true;
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        userLevel: null,
        desc: null,
        province: null,
        city: null,
        zone: null,
        address: null,
        num: null,
        price: null,
        jf: null,
        imgs: null,
        shareImg: null,
        startTime: null,
        endTime: null,
        signTime: null,
        content: null,
        speaker: null,
        signJf: null,
        evaluateJf: null,
        status: null,
        activeStatus: null,
        kf: null,
        shareTimes: null,
        views: null,
        sort: null,
        isIndex: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
      this.area = []
      this.dateRange = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getActivity(id).then(response => {
        this.form = response.data
        const {province,city,zone,startTime,endTime} = response.data;
        this.area = [province,city,zone]
        this.dateRange = [startTime,endTime]
        this.open = true
        this.title = "修改信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除信息编号为"' + ids + '"的数据项？').then(function() {
        return delActivity(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/activity/export', {
        ...this.queryParams
      }, `activity_${new Date().getTime()}.xlsx`)
    },
    // 状态修改
    handleStatusChange(row, field) {
      let text = row[field] == 0 ? "停用" : "启用"
      this.$modal.confirm(`确认要"${text}"${row.title}吗？`).then(function() {
        return updateActivity({id :row.id, [field]: row[field]})
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row[field] = row[field] == "0" ? 1 : 0
      })
    },
    beforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 5
      if (!isRightSize) {
        this.$message.error('文件大小超过 5MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
    uploadSuccess(res,field){
      this.form[field] = res.path;
    },
    handleAreaChange(value) {
      // 检查是否选择了完整的省市区
      if (value.length === 3) {
        // 使用 CodeToText 对象将代码转换为名称
        this.form.province = value[0];
        this.form.city = value[1];
        this.form.zone = value[2];
      } else {
        // 如果未选择完整，则清空名称
        this.form.province = '';
        this.form.city = '';
        this.form.zone = '';
      }
    },
    handleDateRange(value){
      this.form.startTime = value[0];
      this.form.endTime = value[1];
    }
  }
}
</script>
